<!-- src/views/Subscription.vue -->
<template>
  <div class="subscription-page">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="header-left">
        <h1 class="logo">🌐 VPN Manager</h1>
        <nav class="nav-menu">
          <router-link to="/dashboard" class="nav-item" :class="{ active: $route.path === '/dashboard' }">
            仪表板
          </router-link>
          <router-link to="/subscription" class="nav-item" :class="{ active: $route.path === '/subscription' }">
            订阅管理
          </router-link>
          <router-link to="/nodes" class="nav-item" :class="{ active: $route.path === '/nodes' }">
            节点列表
          </router-link>
          <router-link to="/usage" class="nav-item" :class="{ active: $route.path === '/usage' }">
            使用记录
          </router-link>
        </nav>
      </div>
      <div class="header-right">
        <div class="user-menu">
          <span class="user-name">{{ authStore.user?.email }}</span>
          <div class="user-avatar">
            {{ authStore.user?.email?.charAt(0).toUpperCase() }}
          </div>
          <button @click="logout" class="logout-btn">退出</button>
        </div>
      </div>
    </header>

    <div class="page-content">
      <header class="page-header">
        <h1>📋 订阅管理</h1>
        <p>购买和管理您的VPN订阅套餐</p>
      </header>

      <div class="content-grid">
        <!-- 当前订阅状态 -->
        <div class="card current-subscription-card" v-if="currentSubscription">
          <div class="card-header">
            <h2>🎯 当前订阅</h2>
            <span class="card-badge success">活跃</span>
          </div>
          <div class="card-content">
            <div class="subscription-details">
              <div class="detail-grid">
                <div class="detail-item">
                  <label>套餐名称</label>
                  <p class="plan-name">{{ currentSubscription.subscription?.name || '标准套餐' }}</p>
                </div>
                <div class="detail-item">
                  <label>到期时间</label>
                  <p class="expiry-date">{{ formatDate(currentSubscription.expires_at) }}</p>
                </div>
                <div class="detail-item">
                  <label>流量限制</label>
                  <p>{{ formatTraffic(currentSubscription.subscription?.traffic_mb) }}</p>
                </div>
                <div class="detail-item">
                  <label>已用流量</label>
                  <p>{{ formatTraffic(currentSubscription.used_traffic_mb) }}</p>
                </div>
              </div>

              <div class="progress-section">
                <div class="progress-info">
                  <span>使用进度</span>
                  <span>{{ getUsagePercentage() }}%</span>
                </div>
                <div class="progress-bar">
                  <div
                      class="progress-fill"
                      :style="{ width: getUsagePercentage() + '%' }"
                      :class="getUsageClass()"
                  ></div>
                </div>
              </div>

              <div class="action-buttons">
                <button @click="handleRenewSubscription" class="btn primary">
                  🔄 续费订阅
                </button>
                <button @click="showUsageHistory" class="btn secondary">
                  📊 使用记录
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 无订阅状态 -->
        <div class="card no-subscription-card" v-else>
          <div class="card-header">
            <h2>📭 暂无订阅</h2>
            <span class="card-badge danger">未激活</span>
          </div>
          <div class="card-content">
            <div class="empty-state">
              <div class="empty-icon">🔒</div>
              <h3>您还没有激活的订阅</h3>
              <p>购买套餐以开启VPN服务</p>
            </div>
          </div>
        </div>

        <!-- 可用套餐 -->
        <div class="card plans-card">
          <div class="card-header">
            <h2>💰 可用套餐</h2>
            <span class="plans-count">{{ subscriptions.length }} 个套餐</span>
          </div>
          <div class="card-content">
            <div class="plans-grid">
              <div
                  v-for="plan in subscriptions"
                  :key="plan.id"
                  class="plan-card"
                  :class="{ 'recommended': plan.is_recommended }"
              >
                <div class="plan-header">
                  <h3>{{ plan.name }}</h3>
                  <div class="plan-price">
                    <span class="price">¥{{ plan.price }}</span>
                    <span class="period">/{{ plan.duration_days }}天</span>
                  </div>
                  <div v-if="plan.is_recommended" class="recommended-badge">
                    推荐
                  </div>
                </div>

                <div class="plan-features">
                  <div class="feature">
                    <span class="icon">📊</span>
                    <span>流量: {{ formatTraffic(plan.traffic_mb) }}</span>
                  </div>
                  <div class="feature">
                    <span class="icon">⏰</span>
                    <span>时长: {{ plan.duration_days }} 天</span>
                  </div>
                  <div class="feature">
                    <span class="icon">🌐</span>
                    <span>支持所有节点</span>
                  </div>
                </div>

                <button
                    @click="purchasePlan(plan)"
                    class="purchase-btn"
                    :class="{ 'primary': !plan.is_recommended, 'recommended': plan.is_recommended }"
                >
                  {{ currentSubscription ? '升级套餐' : '立即购买' }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 订阅历史 -->
        <div class="card history-card">
          <div class="card-header">
            <h2>📈 订阅历史</h2>
          </div>
          <div class="card-content">
            <div v-if="userSubscriptions.length > 0" class="history-list">
              <div
                  v-for="subscription in userSubscriptions"
                  :key="subscription.id"
                  class="history-item"
              >
                <div class="history-info">
                  <h4>{{ subscription.subscription?.name || '未知套餐' }}</h4>
                  <p class="period">
                    {{ formatDate(subscription.created_at) }} - {{ formatDate(subscription.expires_at) }}
                  </p>
                  <div class="status-badge" :class="subscription.is_active ? 'active' : 'expired'">
                    {{ subscription.is_active ? '活跃' : '已过期' }}
                  </div>
                </div>
                <div class="history-stats">
                  <span class="traffic">
                    {{ formatTraffic(subscription.used_traffic_mb) }} /
                    {{ formatTraffic(subscription.subscription?.traffic_mb) }}
                  </span>
                </div>
              </div>
            </div>
            <div v-else class="empty-history">
              <p>暂无订阅历史</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/modules/auth'
import { getSubscriptions, purchaseSubscription } from '@/api/vpn'

const router = useRouter()
const authStore = useAuthStore()

const subscriptions = ref([])
const loading = ref(false)

const userSubscriptions = computed(() => authStore.userSubscriptions)
const currentSubscription = computed(() => authStore.currentSubscription)

onMounted(async () => {
  await loadSubscriptions()
})

const loadSubscriptions = async () => {
  try {
    const response = await getSubscriptions()
    if (response.data && Array.isArray(response.data)) {
      subscriptions.value = response.data
    } else {
      // 使用模拟数据
      subscriptions.value = getMockSubscriptions()
    }
  } catch (error) {
    console.error('加载套餐失败:', error)
    // 使用模拟数据
    subscriptions.value = getMockSubscriptions()
    alert('加载套餐信息失败，使用模拟数据展示')
  }
}

// 模拟套餐数据
const getMockSubscriptions = () => {
  return [
    {
      id: 1,
      name: '基础套餐',
      price: 9.9,
      duration_days: 30,
      traffic_mb: 10240,
      is_recommended: false
    },
    {
      id: 2,
      name: '标准套餐',
      price: 19.9,
      duration_days: 30,
      traffic_mb: 51200,
      is_recommended: true
    },
    {
      id: 3,
      name: '高级套餐',
      price: 29.9,
      duration_days: 30,
      traffic_mb: 102400,
      is_recommended: false
    }
  ]
}

const purchasePlan = async (plan) => {
  if (!confirm(`确定要购买 ${plan.name} 套餐吗？`)) return

  loading.value = true
  try {
    const response = await purchaseSubscription({
      subscription_id: plan.id
    })

    alert('购买成功！')
    await authStore.fetchUserData()
  } catch (error) {
    console.error('购买失败:', error)
    alert(error.response?.data?.detail || '购买失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重命名这个函数，避免与导入的冲突
const handleRenewSubscription = async () => {
  if (!currentSubscription.value) return

  if (!confirm('确定要续费当前订阅吗？')) return

  try {
    // 这里需要调用续费的API，但你的API中没有续费接口
    // 暂时使用购买接口作为替代
    const response = await purchaseSubscription({
      subscription_id: currentSubscription.value.subscription_id
    })
    alert('续费成功！')
    await authStore.fetchUserData()
  } catch (error) {
    console.error('续费失败:', error)
    alert(error.response?.data?.detail || '续费失败，请重试')
  }
}

const showUsageHistory = () => {
  router.push('/usage')
}

const logout = () => {
  authStore.clearToken()
  router.push('/login')
}

const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const formatTraffic = (mb) => {
  if (!mb) return '0 MB'
  if (mb < 1024) return `${mb} MB`
  return `${(mb / 1024).toFixed(2)} GB`
}

const getUsagePercentage = () => {
  if (!currentSubscription.value || !currentSubscription.value.subscription?.traffic_mb) return 0
  const total = currentSubscription.value.subscription.traffic_mb
  const used = currentSubscription.value.used_traffic_mb || 0
  return Math.min(100, Math.round((used / total) * 100))
}

const getUsageClass = () => {
  const percentage = getUsagePercentage()
  if (percentage < 80) return 'normal'
  if (percentage < 95) return 'warning'
  return 'danger'
}
</script>

<style scoped>
.subscription-page {
  min-height: 100vh;
  background: #f5f7fa;
}

/* 顶部导航样式 - 与Dashboard保持一致 */
.dashboard-header {
  background: white;
  padding: 0 30px;
  border-bottom: 1px solid #e1e5e9;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 40px;
}

.logo {
  font-size: 20px;
  font-weight: 700;
  color: #1890ff;
  margin: 0;
}

.nav-menu {
  display: flex;
  gap: 30px;
}

.nav-item {
  text-decoration: none;
  color: #666;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.3s;
}

.nav-item.active {
  background: #1890ff;
  color: white;
}

.nav-item:hover:not(.active) {
  background: #f0f0f0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-menu {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-name {
  color: #333;
  font-weight: 500;
}

.user-avatar {
  width: 36px;
  height: 36px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
}

.logout-btn {
  padding: 6px 12px;
  border: 1px solid #dc3545;
  background: white;
  color: #dc3545;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  background: #dc3545;
  color: white;
}

.page-content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

.content-grid {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 卡片样式 */
.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.card-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.card-content {
  padding: 24px;
}

/* 当前订阅样式 */
.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.detail-item label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.detail-item p {
  margin: 0;
  color: #333;
  font-weight: 500;
}

.plan-name {
  color: #1890ff;
  font-size: 16px;
  font-weight: 700;
}

.expiry-date {
  color: #faad14;
  font-weight: 700;
}

.progress-section {
  margin-bottom: 24px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.progress-bar {
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 4px;
  transition: width 0.3s;
}

.progress-fill.normal {
  background: linear-gradient(90deg, #52c41a, #73d13d);
}

.progress-fill.warning {
  background: linear-gradient(90deg, #faad14, #ffc53d);
}

.progress-fill.danger {
  background: linear-gradient(90deg, #ff4d4f, #ff7875);
}

.action-buttons {
  display: flex;
  gap: 12px;
}

/* 套餐网格 */
.plans-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.plan-card {
  border: 2px solid #f0f0f0;
  border-radius: 12px;
  padding: 24px;
  transition: all 0.3s;
  position: relative;
}

.plan-card.recommended {
  border-color: #1890ff;
  transform: scale(1.02);
}

.plan-header {
  margin-bottom: 20px;
  position: relative;
}

.plan-header h3 {
  margin: 0 0 12px 0;
  color: #333;
}

.plan-price {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.price {
  font-size: 24px;
  font-weight: 700;
  color: #1890ff;
}

.period {
  color: #666;
  font-size: 14px;
}

.recommended-badge {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #1890ff;
  color: white;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.plan-features {
  margin-bottom: 20px;
}

.feature {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #666;
}

.feature .icon {
  font-size: 16px;
}

.purchase-btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.purchase-btn.primary {
  background: #1890ff;
  color: white;
}

.purchase-btn.recommended {
  background: #52c41a;
  color: white;
}

.purchase-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

/* 历史记录 */
.history-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.history-info h4 {
  margin: 0 0 4px 0;
  color: #333;
}

.history-info .period {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 500;
}

.status-badge.active {
  background: #f6ffed;
  color: #52c41a;
}

.status-badge.expired {
  background: #fff2f0;
  color: #ff4d4f;
}

.traffic {
  font-size: 12px;
  color: #666;
}

.empty-history {
  text-align: center;
  padding: 40px;
  color: #666;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.empty-state p {
  margin: 0;
  color: #666;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.btn.primary {
  background: #1890ff;
  color: white;
}

.btn.secondary {
  background: white;
  color: #666;
  border: 1px solid #d9d9d9;
}

.btn:hover {
  transform: translateY(-1px);
}

/* 徽章样式 */
.card-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.card-badge.success {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.card-badge.danger {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.plans-count {
  font-size: 12px;
  color: #666;
}
</style>